import React, { useEffect } from 'react'
import ReactECharts from 'echarts-for-react'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import 'echarts-wordcloud'

export interface WordCloudData {
  name: string
  value: number
}

export interface WordCloudProps {
  data: WordCloudData[]
  height?: number | string
  title?: string
}

/**
 * 词云图组件
 * 用于关键词可视化展示
 */
const WordCloud: React.FC<WordCloudProps> = ({
  data,
  height = 400,
  title
}) => {
  console.log('[词云组件] 接收到的数据:', data)
  console.log('[词云组件] 数据长度:', data.length)

  // 确保数据有效
  if (!data || data.length === 0) {
    return (
      <div style={{
        height,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#999'
      }}>
        暂无关键词数据
      </div>
    )
  }

  const option: EChartsOption = {
    title: title ? {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    } : undefined,
    tooltip: {
      show: true,
      formatter: (params: any) => {
        return `<div>
          <div style="font-weight: bold;">${params.name}</div>
          <div>权重: ${params.value}</div>
        </div>`
      }
    },
    series: [{
      type: 'wordCloud' as any,
      shape: 'circle',
      left: 'center',
      top: title ? '60px' : 'center',
      width: '90%',
      height: title ? 'calc(100% - 80px)' : '90%',
      sizeRange: [14, 60],
      rotationRange: [-45, 45],
      rotationStep: 45,
      gridSize: 12,
      drawOutOfBound: false,
      layoutAnimation: true,
      textStyle: {
        fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif',
        fontWeight: 'bold',
        color: () => {
          const colors = [
            '#1890ff', '#52c41a', '#faad14', '#f5222d',
            '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16',
            '#2f54eb', '#a0d911'
          ]
          return colors[Math.floor(Math.random() * colors.length)]
        }
      },
      emphasis: {
        focus: 'self',
        textStyle: {
          textShadowBlur: 10,
          textShadowColor: '#333'
        }
      },
      data: data.map(item => {
        const maxValue = Math.max(...data.map(d => d.value), 1)
        return {
          name: item.name,
          value: item.value,
          textStyle: {
            fontSize: Math.max(14, 14 + (item.value / maxValue) * 46)
          }
        }
      })
    } as any]
  }

  return (
    <ReactECharts
      option={option}
      style={{ height, width: '100%' }}
      opts={{ renderer: 'canvas' }}
    />
  )
}

export default WordCloud
